package com.paradise.phone.fragment;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Fragment;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.paradise.api.FaceCall;
import com.paradise.api.FaceLogin;
import com.paradise.api.FacephonePreferences;
import com.paradise.phone.activity.MainActivity;
import com.paradise.phone.utils.DataBaseHelper;
import com.paradise.phone.utils.Numpad;

import me.majiajie.pagerbottomtabstrip.NavigationController;
import me.majiajie.pagerbottomtabstrip.PageNavigationView;
import me.majiajie.pagerbottomtabstrip.listener.OnTabItemSelectedListener;

public class CallFragment extends Fragment implements View.OnClickListener {

    private View rootView;

    private Numpad numpad;
    private EditText etUserName;
    private ImageView btnCall;
    private Button btnHangup;

    private TextView tvUsername;
    private RadioGroup rgDefaultCallType;
    private ImageView ivDotStatus;

    private RelativeLayout flNumpad;

    private ImageView ivNumpadHide;
    private ImageView ivCallHide;
    private boolean isNumpadHide = false;

    private PageNavigationView nav;
    private NavigationController nc;

    private SQLiteDatabase db;

    public CallFragment() {
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(com.paradise.phone.R.layout.fragment_call, container, false);

        db = DataBaseHelper.instance(getActivity())
                .getWritableDatabase();

        initView();

        initEvent();

        return rootView;
    }

    private void initEvent() {
        numpad.setOnDigitClickListener(new Numpad.OnDigitClickListener() {

            @Override
            public void onDigitClickListener(View view, String s) {
                if (s.equals("cl")) {
                    etUserName.setText("");
                } else if (s.equals("del")) {
                    String tmp = etUserName.getText().toString();
                    if (!TextUtils.isEmpty(tmp))
                        etUserName.setText(tmp.substring(0, tmp.length() - 1));
                } else {
                    etUserName.append(s);
                }

            }

            @Override
            public void onDigitTouchListener(View digit, String num, MotionEvent event) {

            }
        });

        btnCall.setOnClickListener(this);
        btnHangup.setOnClickListener(this);

        tvUsername.setOnClickListener(this);

        rgDefaultCallType.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                switch (checkedId) {
                    case com.paradise.phone.R.id.rb_video_call:
                        FacephonePreferences.instance().setInitiateVideoCall(true);
                        break;
                    case com.paradise.phone.R.id.rb_audio_call:
                        FacephonePreferences.instance().setInitiateVideoCall(false);
                        break;
                }
            }
        });
        ivNumpadHide.setOnClickListener(this);
        ivCallHide.setOnClickListener(this);
    }

    private void initView() {
        numpad = (Numpad) rootView.findViewById(com.paradise.phone.R.id.numpad);
        etUserName = (EditText) rootView.findViewById(com.paradise.phone.R.id.et_input_username);
        btnCall = (ImageView) rootView.findViewById(com.paradise.phone.R.id.btn_call);
        btnHangup = (Button) rootView.findViewById(com.paradise.phone.R.id.btn_numpad_hang_up);
        tvUsername = (TextView) rootView.findViewById(com.paradise.phone.R.id.tv_username);
        rgDefaultCallType = (RadioGroup) rootView.findViewById(com.paradise.phone.R.id.rg_call_type);
        ivDotStatus = (ImageView) rootView.findViewById(com.paradise.phone.R.id.iv_dot_status);
        flNumpad = (RelativeLayout) rootView.findViewById(com.paradise.phone.R.id.include_numpad);
        ivNumpadHide = (ImageView) rootView.findViewById(com.paradise.phone.R.id.btn_numpad_hide);
        ivCallHide = (ImageView) rootView.findViewById(com.paradise.phone.R.id.iv_call);
        nav = (PageNavigationView) rootView.findViewById(com.paradise.phone.R.id.nav);

        nc = nav.material()
                .addItem(com.paradise.phone.R.mipmap.contact, "", Color.WHITE)
                .addItem(com.paradise.phone.R.mipmap.history, "", Color.WHITE)
                .build();

        getFragmentManager().beginTransaction()
                .replace(com.paradise.phone.R.id.fl_container, new ContactFragment())
                .commit();

        nc.addTabItemSelectedListener(new OnTabItemSelectedListener() {
            @Override
            public void onSelected(int index, int old) {
                if (index == 0) {
                    getFragmentManager().beginTransaction()
                            //.setCustomAnimations(R.animator.animator_rotate_in_1, R.animator.animator_rotate_out_1)
                            .replace(com.paradise.phone.R.id.fl_container, new ContactFragment())
                            .commit();
                }else if (index == 1){
                    getFragmentManager().beginTransaction()
                            //.setCustomAnimations(R.animator.animator_rotate_in, R.animator.animator_rotate_out)
                            .replace(com.paradise.phone.R.id.fl_container, new HistoryFragment())
                            .commit();
                }

            }

            @Override
            public void onRepeat(int index) {

            }
        });

        syncStatusFromActivity();

        if (FacephonePreferences.instance().shouldInitiateVideoCall()) {
            rgDefaultCallType.check(com.paradise.phone.R.id.rb_video_call);
        } else {
            rgDefaultCallType.check(com.paradise.phone.R.id.rb_audio_call);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case com.paradise.phone.R.id.btn_call:
                Cursor cursor = db.rawQuery("select * from Contact where number = '"
                        +etUserName.getText().toString()+"'", null);

                String displayName;
                if (cursor.getCount() == 0){
                    displayName = "未知联系人";
                }else {
                    cursor.moveToNext();
                    displayName = cursor.getString(1);
                }

                FaceCall.instance().call(getActivity(),
                        etUserName.getText().toString(),
                        displayName);
                break;

            case com.paradise.phone.R.id.btn_numpad_hang_up:
                FaceCall.instance().terminateCurrentCall();
                break;

            case com.paradise.phone.R.id.btn_numpad_hide:
                numpadHide();
                ivCallHide.setVisibility(View.VISIBLE);
                ObjectAnimator scaleX = ObjectAnimator.ofFloat(ivCallHide, "scaleX", 0f, 1.2f, 1f);
                ObjectAnimator scaleY = ObjectAnimator.ofFloat(ivCallHide, "scaleY", 0f, 1.2f, 1f);
                AnimatorSet scale = new AnimatorSet();
                scale.play(scaleX).with(scaleY);
                scale.setDuration(500);
                scale.start();
                break;

            case com.paradise.phone.R.id.iv_call:
                ObjectAnimator shrinkX = ObjectAnimator.ofFloat(ivCallHide, "scaleX", 1f, 0f);
                ObjectAnimator shrinkY = ObjectAnimator.ofFloat(ivCallHide, "scaleY", 1f, 0f);
                AnimatorSet shrink = new AnimatorSet();
                shrink.play(shrinkX).with(shrinkY);
                shrink.setDuration(500);
                shrink.start();
                ivCallHide.setVisibility(View.GONE);
                numpadShow();
                break;

            case com.paradise.phone.R.id.tv_username:

                ((MainActivity)getActivity()).getNavigation().openDrawer(Gravity.LEFT);

                break;
        }
    }


    private int dip2px(float dpValue) {

        float scale = getResources().getDisplayMetrics().density;

        return (int) (dpValue * scale + 0.5f);
    }

    public void numpadShow(){
        if (!isNumpadHide)
            return;
        isNumpadHide = false;
        ObjectAnimator in = ObjectAnimator.ofFloat(flNumpad, "translationY", (flNumpad.getMeasuredHeight()), 0f);
        in.setDuration(500);
        in.start();
    }

    public void numpadHide(){
        if (isNumpadHide)
            return;
        isNumpadHide = true;
        ObjectAnimator out = ObjectAnimator.ofFloat(flNumpad, "translationY", 0f, (flNumpad.getMeasuredHeight()));
        out.setDuration(500);
        out.start();
    }

    /**
     * 从activity中同步登陆状态
     */
    public void syncStatusFromActivity() {
        if (((MainActivity) getActivity()).getStatus().toString().equals("在线")) {
            ivDotStatus.setImageResource(com.paradise.phone.R.mipmap.dot_online);
            if (FaceLogin.instance().getCurrentAuthInfo() != null) {
                tvUsername.setText(FaceLogin.instance().getCurrentAuthInfo().getUsername() + " 在线");
            }
        } else {
            ivDotStatus.setImageResource(com.paradise.phone.R.mipmap.dot_offline);
            if (FaceLogin.instance().getCurrentAuthInfo() != null) {
                tvUsername.setText(FaceLogin.instance().getCurrentAuthInfo().getUsername() + " 离线");
            } else {
                tvUsername.setText("请先登录");
            }
        }
    }
}
